package com.ktjiaoyu.server.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjiaoyu.server.domain.pojo.Admin;
import com.ktjiaoyu.server.service.AdminService;
import com.ktjiaoyu.server.utils.PageUtil;
import com.ktjiaoyu.server.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "Admin相关接口")
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired // 注入加密工具类的bean实例对象
    private PasswordEncoder passwordEncoder;

//    @ApiOperation(value = "")
//    @GetMapping("/list")
//    public Object admin() {
//        List<Admin> list = adminService.list();
//        return list;
//    }


    @GetMapping("/list")
    public ResponseResult getPageUserList(
            @RequestParam(value = "currPageNo", defaultValue = "1") Integer currPageNo,
            @RequestParam(value = "pageSize", defaultValue = "4")Integer pageSize,
            @RequestParam(value = "name", required = false) String name,
             @RequestParam(value = "sort") String sort) {

        Page<Admin> page = new Page<Admin>(currPageNo, pageSize);
        IPage<Admin> adminIPage = adminService.selectByPage(page,name,sort);
        // 使用Math.toIntExact将Long类型转换成int类型
        Integer total = Math.toIntExact(adminIPage.getTotal());
        Integer current = Math.toIntExact(adminIPage.getCurrent());
        PageUtil<Admin> pageList = new PageUtil<Admin>(total,current,adminIPage.getRecords());
        return ResponseResult.success("获取操作员列表成功", pageList);
    }


    @PostMapping("/updateState")
    public ResponseResult updateState(@RequestBody Admin admin) {

           adminService.updataAdmin(admin);

        return ResponseResult.success("修改操作员状态成功");

    }

    @PostMapping("/saveAdmin")
    public ResponseResult saveAdmin(@RequestBody Admin admin) {
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));

        if (adminService.saveAdmin(admin)) {
            return ResponseResult.success("保存操作员新增信息成功");
        }else {
            return ResponseResult.success("保存操作员信息失败");
        }
    }

    @GetMapping("/info")
    public ResponseResult userInfo() {
      Admin admin =  adminService.getUserInfo();

      return ResponseResult.success(admin);
    }



    //登出功能
    @ApiOperation(value = "登出接口")
    @PostMapping("/doLogout")
    public ResponseResult doLogout(){
        adminService.logout();
        return ResponseResult.success();
    }

}
